package com.io.util;

import com.io.model.RegisterReq;
import com.io.protocol.CommonConstants;
import com.io.protocol.LengthConstants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

import java.nio.charset.Charset;

/**
 * Created by yangyx on 2016/7/21.
 */
public class NettyUtils {

    private static Charset utf8Charset = Charset.forName("UTF-8");

    public static String readStringFromByteBuf(ByteBuf buf, int len){
        byte[] bytes = new byte[len];
        buf.readBytes(bytes, 0, len);
        return new String(bytes, utf8Charset);
    }

    public static void writeBlankToByteBuf(ByteBuf buf, int len){
        for(int i=0; i<len; i++){
            buf.writeByte(' ');
        }
    }

    /*//len为0时表示长度不固定,否则表示固定长度,长度超过时截掉,长度不足时后补空格
    public static void writeStringToByteBuf(ByteBuf buf, String str, int len){
        //Encoder.UTF_8.ge
        byte[] bytes = str.getBytes(utf8Charset);
        if(len!=0){
            if(bytes.length==len){
                buf.writeBytes(bytes);
            }
            else if(bytes.length<len){
                buf.writeBytes(bytes);
                NettyUtils.writeBlankToByteBuf(buf, len-bytes.length);
            }
            else { //bytes.length>len
                buf.writeBytes(bytes, 0, len);
            }
        }
        else{
            buf.writeBytes(bytes);
        }
    }*/

    //检查CRC 算法 - CRC-CCITT (0xFFFF)
    public static short calculateCrc(ByteBuf buf, int beginIdx, int endIdx){
        short crcCal = (short) 0xFFFF;
        for (int i = beginIdx; i < endIdx; i++) {
            byte b = buf.getByte(i);
            for (int j = 0; j < 8; j++) {
                boolean c15 = (crcCal >> 15 & 1) == 1;
                boolean bit = (b >> (7 - j) & 1) == 1;
                crcCal <<= 1;
                if (c15 ^ bit) crcCal ^= 0x1021;
            }
        }
        return crcCal;
    }
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/4 9:54
     *验证两个通道是否是同一个通道
     */
    public static boolean isChannelEqual(ChannelHandlerContext ctx1, ChannelHandlerContext ctx2){
        if(ctx1!=null && ctx2!=null) {
            return ctx1.channel().id().asLongText().equals(ctx2.channel().id().asLongText());
        }
        return false;
    }
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/4 10:03
     *验证当前状态是否已经登录
     */
    public static boolean checkLoginStatus(ChannelHandlerContext ctx){
        RegisterReq LoginObj= (RegisterReq) ctx.channel().attr(CommonConstants.ATTRIBUTE_KEY);
        if(null==LoginObj) return false;
        return true;
    }

}
